<?php
declare(strict_types=1);

use Phinx\Migration\AbstractMigration;

final class AddCustomDesignMakeWayInAttributeTable extends AbstractMigration
{
    /**
     * 获取所有模块数据
     * @return array
     */
    public function getAllModuleData()
    {
        $sql = 'select * from module';
        $result = $this->query($sql);
        $info = array();
        foreach ($result as $key => $val) {
            $info[$val['code']] = $val;
        }
        return $info;
    }


    /**
     * 获取所有属性数据
     * @return array
     */
    public function getAllAttributeData()
    {
        $sql = 'select * from attribute';
        $result = $this->query($sql);
        $info = array();
        foreach ($result as $key => $val) {
            $info[$val['code']] = $val;
        }
        return $info;
    }

    /**
     * 判断当前字段是否为必须
     * @param $field
     * @return string
     */
    public function checkFieldRequire($field)
    {
        if (in_array($field, ['name', 'phone', 'password', 'value', 'ptype', 'status', 'man_hour', 'type', 'attribute_value'])) {
            return 'yes';
        }

        if (strpos($field, '_id')) {
            return 'yes';
        }

        return 'no';
    }

    /**
     * 判断当前字段是否能编辑
     * @param $field
     * @return string
     */
    public function checkFieldEdit($field)
    {
        if (in_array($field, ['id', 'uuid', 'created_by', 'created', 'json', 'is_horizontal'])) {
            return 'deny';
        }

        if (strpos($field, '_id')) {
            return 'deny';
        }

        return 'allow';
    }

    /**
     * 判断当前字段是否能显示
     * @param $field
     * @return string
     */
    public function checkFieldShow($field)
    {
        if (in_array($field, ['json', 'password'])) {
            return 'no';
        }

        return 'yes';
    }


    /**
     * 判断当前字段是否能排序
     * @param $field
     * @return string
     */
    public function checkFieldSort($field)
    {
        if (in_array($field, ['name', 'code', 'attribute_id', 'start_time', 'end_time', 'type', 'created_by', 'created', 'project_id', 'category_id', 'step_category_id'])) {
            return 'allow';
        }


        return 'deny';
    }


    /**
     * 判断当前字段是否能分组
     * @param $field
     * @return string
     */
    public function checkFieldGroup($field)
    {
        if (strpos($field, '_id')) {
            return 'allow';
        }

        return 'deny';
    }

    /**
     * 判断当前字段是否能过滤
     * @param $field
     * @return string
     */
    public function checkFieldFilter($field)
    {
        if (in_array($field, ['id', 'uuid', 'json', 'config', 'param', 'admin_password', 'node_config'])) {
            return 'deny';
        }

        return 'allow';
    }

    /**
     * 判断当前字段是否能过滤
     * @param $field
     * @return string
     */
    public function checkFieldPrimaryKey($field)
    {
        if ($field === 'id') {
            return 'yes';
        }

        return 'no';
    }

    /**
     * 判断当前字段是否能过滤
     * @param $field
     * @return string
     */
    public function checkFieldForeignKey($field)
    {
        if (strpos($field, '_id')) {
            return 'yes';
        }

        return 'no';
    }

    /**
     * _ 名称转驼峰
     * @param $unCamelizeWords
     * @param string $separator
     * @return mixed
     */
    public function camelize($unCamelizeWords, $separator = '_')
    {
        $unCamelizeWords = $separator . str_replace($separator, " ", strtolower($unCamelizeWords));
        return str_replace(" ", "", ucwords(ltrim($unCamelizeWords, $separator)));
    }

    /**
     * 生成字段配置
     * @param $modelName
     * @param $realName
     * @param $moduleID
     * @param $field
     * @param $dataSource
     * @param $type
     * @return array
     */
    public function generateFieldConfig($modelName, $realName, $moduleID, $field, $dataSource, $type)
    {
        $fieldConfig = [
            "id" => 0, // 字段id, 固定字段是0，自定义字段是注册的id值
            "field" => $field, // 字段名
            "type" => $type, //字段类型
            "field_type" => "custom", //字段类型 built_in：固定字段，custom：自定义字段
            "disabled" => "no", // 是否禁用（yes, no）
            "require" => $this->checkFieldRequire($field), // 是否必须（yes, no）
            "table" => $modelName, // 所属表名
            "module_code" => $realName, // 所属模块名
            "module_id" => $moduleID, // 模块id
            "lang" => strtoupper($field), // 语言包KEY
            "editor" => "select", // 编辑器类型 下拉框
            "edit" => $this->checkFieldEdit($field), // 是否可以编辑（allow, deny）
            "show" => $this->checkFieldShow($field), // 是否在前台显示 （yes, no）
            "sort" => $this->checkFieldSort($field), // 是否可以排序（allow, deny）
            "group" => $this->checkFieldGroup($field), // 是否可以分组
            "group_name" => "", // 分组显示名称
            "filter" => $this->checkFieldFilter($field), // 是否可以过滤（allow, deny）
            "multiple" => "no", // 是否可以多选（yes, no）
            "format" => [], // 格式化配置
            "validate" => "", // 验证方法
            "mask" => "", // 掩码配置
            "is_primary_key" => $this->checkFieldPrimaryKey($field), // 是否是主键（yes, no）
            "is_foreign_key" => $this->checkFieldForeignKey($field), // 是否是外键（yes, no）
            "placeholder" => "no", // 输入框占位文本 （yes, no）
            "show_word_limit" => "no", // 是否显示输入字数统计 （yes, no）
            "autocomplete" => "no", // 是否自动补全 （yes, no）
            "value_icon" => "", // 值图标
            "label_icon" => "", // 文本图标
            "label_width" => 0, // 文本宽度
            "value_width" => 0, //  值宽度
            "is_label" => "no",  //  是否显示文本 （yes, no）
            "default_value" => "", // 默认值
            "data_source" => $dataSource
        ];

        return $fieldConfig;
    }


    protected $attributeTable;

    protected $attributeValueTable;

    protected $stepCategoryAttributeTable;

    /**
     * 获取所有工序分类数据
     * @return array
     */
    public function getAllStepCategoryData()
    {
        $sql = 'select * from step_category';
        $result = $this->query($sql);
        $info = array();
        foreach ($result as $key => $val) {
            $info[$val['code']] = $val;
        }
        return $info;
    }


    /**
     * 递归添加属性和属性值
     * @param $attributeData
     * @param $allStepCategoryData
     * @throws Exception
     */
    public function recursionAttribute($attributeData, $allStepCategoryData)
    {
        foreach ($attributeData as $attributeItem) {
            $attributeAdd = $attributeItem['data'];
            $attributeAdd['uuid'] = Webpatser\Uuid\Uuid::generate()->string;
            $this->attributeTable->insert($attributeAdd)->save();
            $query = $this->fetchRow('SELECT max(`id`) as id FROM attribute');

            // 工序分类关联属性
            foreach ($attributeItem['module_code'] as $moduleCode) {
                $stepCategoryAttributeItem = [
                    'attribute_id' => $query['id'],
                    'step_category_id' => $allStepCategoryData[$moduleCode]['id']
                ];

                $this->stepCategoryAttributeTable->insert($stepCategoryAttributeItem)->save();
            }

            foreach ($attributeItem['values'] as $value => $variable) {
                $attributeValueAdd = [
                    'value' => $value,
                    'attribute_id' => $query['id'],
                    'variable' => $variable,
                    'uuid' => Webpatser\Uuid\Uuid::generate()->string
                ];
                $this->attributeValueTable->insert($attributeValueAdd)->save();
            }
        }
    }


    /**
     * Change Method.
     *
     * Write your reversible migrations using this method.
     *
     * More information on writing migrations is available here:
     * https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
     *
     * Remember to call "create()" or "update()" and NOT "save()" when working
     * with the Table class.
     */
    public function change(): void
    {

        $attributeData = [
            [
                'module_code' => ['design_entity'],
                'data' => [
                    'name' => '美术制作方式',
                    'code' => 'meishuzhizuofangshi'
                ],
                'values' => [
                    '概念稿' => 1,
                    '不出图' => 1,
                ]
            ],
            [
                'module_code' => ['model'],
                'data' => [
                    'name' => '毛发制作',
                    'code' => 'maofazhizuo'
                ],
                'values' => [
                    '有毛发' => 1,
                    '无毛发' => 1,
                ]
            ],
            [
                'module_code' => ['design_entity'],
                'data' => [
                    'name' => '特效制作',
                    'code' => 'texiaozhizuo'
                ],
                'values' => [
                    '场景特效' => 1,
                    '材质特效' => 1,
                    '无特效制作' => 1,
                ]
            ],
            [
                'module_code' => ['comp'],
                'data' => [
                    'name' => '合成方式',
                    'code' => 'hechengfangshi'
                ],
                'values' => [
                    '有合成' => 1,
                    '无合成' => 1,
                ]
            ]
        ];


        $allStepCategoryData = $this->getAllStepCategoryData();
        $this->attributeTable = $this->table('attribute');
        $this->attributeValueTable = $this->table('attribute_value');
        $this->stepCategoryAttributeTable = $this->table('step_category_attribute');

        $this->recursionAttribute($attributeData, $allStepCategoryData);


        $moduleMap = $this->getAllModuleData();

        $entityAttributeCustomFields = [
            'design' => [
                'meishuzhizuofangshi' => [
                    'field' => 'design_production_method', // 制作方式
                    'table' => 'entity',
                ],
                'maofazhizuo' => [
                    'field' => 'design_hair_making', // 毛发制作
                    'table' => 'entity',
                ],
                'texiaozhizuo' => [
                    'field' => 'design_fx_production', // 特效制作
                    'table' => 'entity',
                ],
                'design_is_publishing' => [
                    'field' => 'design_is_publishing', // 是否发布
                    'table' => 'entity',
                ],
            ],
            'asset' => [
                'meishuzhizuofangshi' => [
                    'field' => 'asset_production_method', // 制作方式
                    'table' => 'entity',
                ],
                'maofazhizuo' => [
                    'field' => 'asset_hair_making', // 毛发制作
                    'table' => 'entity',
                ],
                'texiaozhizuo' => [
                    'field' => 'asset_fx_production', // 特效制作
                    'table' => 'entity',
                ],
            ],
            'level' => [
                'meishuzhizuofangshi' => [
                    'field' => 'level_production_method', // 制作方式
                    'table' => 'entity',
                ],
                'maofazhizuo' => [
                    'field' => 'level_hair_making', // 毛发制作
                    'table' => 'entity',
                ],
                'texiaozhizuo' => [
                    'field' => 'level_fx_production', // 特效制作
                    'table' => 'entity',
                ],
            ],
            'storyboard' => [
                'storyboard_is_publishing' => [
                    'field' => 'storyboard_is_publishing', // 是否发布
                    'table' => 'entity',
                ],
                'hechengfangshi' => [
                    'field' => 'storyboard_comp_type', // 合成方式
                    'table' => 'entity',
                ],
            ],
            'shot' => [
                'hechengfangshi' => [
                    'field' => 'shot_comp_type', // 合成方式
                    'table' => 'entity',
                ],
            ],
            'review_feedback_entity' => [
                'meishuzhizuofangshi' => [
                    'field' => 'review_feedback_entity_production_method', // 制作方式
                    'table' => 'review_feedback_entity',
                ],
                'maofazhizuo' => [
                    'field' => 'review_feedback_entity_hair_making', // 毛发制作
                    'table' => 'review_feedback_entity',
                ],
                'texiaozhizuo' => [
                    'field' => 'review_feedback_entity_fx_production', // 特效制作
                    'table' => 'review_feedback_entity',
                ],
                'buliaojiesuan' => [
                    'field' => 'review_feedback_entity_cloth_solution', // 布料解算
                    'table' => 'review_feedback_entity',
                ],
                'texiaoleixing' => [
                    'field' => 'review_feedback_entity_fx', // 特效
                    'table' => 'review_feedback_entity',
                ],
                'review_feedback_entity_draft_data' => [
                    'field' => 'review_feedback_entity_draft_data', // 草稿数据
                    'table' => 'review_feedback_entity',
                ],
                'hechengfangshi' => [
                    'field' => 'review_feedback_entity_comp_type', // 合成方式
                    'table' => 'review_feedback_entity',
                ],
            ]
        ];

        $attributeMap = $this->getAllAttributeData();

        foreach ($entityAttributeCustomFields as $moduleCode => $entityAttributeData) {
            $moduleData = $moduleMap[$moduleCode];
            foreach ($entityAttributeData as $attributeCode => $attributeCustomField) {


                $fieldData = [
                    'is_horizontal' => 0,
                    'module_id' => $moduleData['id'],
                    'type' => 'custom',
                    'table' => $attributeCustomField['table'],
                    'uuid' => Webpatser\Uuid\Uuid::generate()->string
                ];

                $attributeData = $attributeMap[$attributeCode] ?? null;

                $type = '';
                if (!empty($attributeData)) {
                    $dataSource = [ // 数据源
                        "type" => "api", // 数据源类型，fixed 固定 , api 动态
                        "data" => "attribute_{$attributeCode}", // 数据源，静态直接配置，动态是一个字符串标识
                        "module_id" => $moduleData['id'],
                        "attribute_id" => $attributeData['id']
                    ];
                    $type = 'attribute';
                } else {
                    $dataSource = [ // 数据源
                        "type" => "fixed", // 数据源类型，fixed 固定 , api 动态
                        "data" => []
                    ];
                    $type = 'string';
                }

                $fieldConfig = $this->generateFieldConfig($attributeCustomField['table'], $moduleData['code'], $moduleData['id'], $attributeCustomField['field'], $dataSource, $type);
                $fieldData['config'] = json_encode($fieldConfig);
                $rows[] = $fieldData;
            }
        }


        // 写入字段数据表
        $this->table('field')->insert($rows)->save();

    }
}
